const express = require('express')
const bodyParser = require('body-parser')
const multer = require('multer')
const db = require('./utils/db.js')

//创建服务器
let app = express();

//创建上传组件,用来保存指定图片的路径
const upload = multer({
    dest: './web/uploads/'
})

//注册中间件
//暴露静态文件
app.use(express.static('web'))
app.use(bodyParser.urlencoded({
    extended: false
}))
app.use(bodyParser.json())

//注册路由
//登录
app.post('/user/login', (req, res) => {
    // let msgData={
    //     code:200,
    //     msg:"登录成功"
    // }
    let msgData = getMsgData(200, '登录成功')
    if (req.body.username != 'admin' || req.body.password != '123456') {
        msgData.code = 400;
        msgData.msg = "用户名或者密码错误"
    }
    res.send(msgData)
})

//所有英雄数据 路由
app.get('/hero/all', (req, res) => {
    let heroObj = db.getHeros();
    let msgData = getMsgData('200', '数据获取成功', heroObj)
    if (heroObj == null) {
        msgData.code = 400;
        msgData.msg = "数据获取失败"
    }
    res.send(msgData)
})

function getMsgData(code, msg, data = null) {
    return {
        code,
        msg,
        data,
    }
}
//根据id获取英雄
app.get('/hero/id', (req, res) => {
    //获取id
    let sId = req.query.id;
    let heroObj = db.getHeroById(sId);
    let msgData = getMsgData('200', '获取成功', heroObj);
    if (heroObj == null) {
        msgData.code = 400;
        msgData.msg = '获取数据失败'
    }
    res.send(msgData)
})

//新增英雄 路由
app.post('/hero/add',upload.single('icon'),(req,res)=>{
    let msgData=getMsgData('201','新增成功')
    
    if (req.body.name==''||req.body.skill==''||req.file==undefined) {
        msgData.code='407';
        msgData.msg="数据缺失,请检查"
    }else {
        let heroData={
            name:req.body.name,
            skill:req.body.skill,
            icon:req.file.filename,
        }
        //将数据添加到数据库中
        let isOk=db.addHero(heroData);
        if (!isOk) {
            msgData.code=400;
            msgData.msg='新增失败';
        }
        res.send(msgData)
    }

})

//删除英雄 路由
app.get('/hero/delete',(req,res)=>{
    let msgData=getMsgData('200','删除成功');
    let sId=req.query.id;
    let isOk=db.deleteHeroById(sId);
    if (!isOk) {
        msgData.code=400;
        msgData.msg='删除失败';
    }
    res.send(msgData)
})

//编辑英雄 路由
app.post('/hero/update',upload.single('icon'),(req,res)=>{

    console.log(req.file);
    console.log(req.files);
    
    let msgData=getMsgData('202',"修改成功")
    let editData={
        skill:req.body.skill,
        name:req.body.name,
        id:req.body.id,
        icon:req.file.filename,
    }
    let isOk=db.editHero(editData);
    if (!isOk) {
        msgData.code=400;
        msgData.msg='修改失败';
    }
    res.send(msgData)

})











//开启服务器
const PORT = 3800;
app.listen(PORT, (err) => {
    if (err == null) {
        console.log('服务器已开启成功' + PORT);

    } else {
        console.log('服务器开启失败' + err.message);
    }
})